"""
数据库接口定义
=============
定义数据库操作的抽象接口，所有数据库实现都必须遵循此接口
"""

from abc import ABC, abstractmethod
from typing import List, Optional, Dict, Any, Union, AsyncContextManager
from contextlib import asynccontextmanager


class TransactionInterface(ABC):
    """事务接口"""
    
    @abstractmethod
    async def commit(self) -> bool:
        """提交事务"""
        pass
    
    @abstractmethod
    async def rollback(self) -> bool:
        """回滚事务"""
        pass
    
    @abstractmethod
    async def execute_query(self, query: str, params: Dict[str, Any] = None) -> List[Dict[str, Any]]:
        """在事务中执行查询"""
        pass
    
    @abstractmethod
    async def execute_command(self, command: str, params: Dict[str, Any] = None) -> int:
        """在事务中执行命令，返回受影响的行数"""
        pass


class DatabaseInterface(ABC):
    """数据库接口定义"""
    
    @abstractmethod
    async def connect(self) -> bool:
        """建立数据库连接"""
        pass
    
    @abstractmethod
    async def disconnect(self) -> bool:
        """断开数据库连接"""
        pass
    
    @abstractmethod
    async def is_connected(self) -> bool:
        """检查连接状态"""
        pass
    
    @abstractmethod
    async def execute_query(self, query: str, params: Dict[str, Any] = None) -> List[Dict[str, Any]]:
        """执行查询，返回结果列表"""
        pass
    
    @abstractmethod
    async def execute_command(self, command: str, params: Dict[str, Any] = None) -> int:
        """执行命令(INSERT/UPDATE/DELETE)，返回受影响的行数"""
        pass
    
    @abstractmethod
    async def execute_scalar(self, query: str, params: Dict[str, Any] = None) -> Any:
        """执行查询，返回单个值"""
        pass
    
    @abstractmethod
    async def execute_many(self, command: str, params_list: List[Dict[str, Any]]) -> int:
        """批量执行命令"""
        pass
    
    @abstractmethod
    async def begin_transaction(self) -> TransactionInterface:
        """开始事务"""
        pass
    
    @abstractmethod
    @asynccontextmanager
    async def transaction(self) -> AsyncContextManager[TransactionInterface]:
        """事务上下文管理器"""
        pass
    
    @abstractmethod
    async def health_check(self) -> Dict[str, Any]:
        """健康检查"""
        pass


class DatabasePoolInterface(ABC):
    """数据库连接池接口"""
    
    @abstractmethod
    async def get_connection(self) -> DatabaseInterface:
        """获取连接"""
        pass
    
    @abstractmethod
    async def return_connection(self, connection: DatabaseInterface) -> None:
        """归还连接"""
        pass
    
    @abstractmethod
    async def close_all(self) -> None:
        """关闭所有连接"""
        pass
    
    @abstractmethod
    def get_pool_stats(self) -> Dict[str, Any]:
        """获取连接池统计信息"""
        pass
